package com.yinhai.message.implement.email.sender;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import javax.mail.Message;

import com.yinhai.core.common.api.util.ValidateUtil;
import org.simplejavamail.email.Email;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.config.TransportStrategy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.yinhai.core.app.api.util.ServiceLocator;
import com.yinhai.core.common.api.config.impl.SysConfig;
import com.yinhai.message.api.bean.TMUser;
import com.yinhai.message.api.exception.TMException;
import com.yinhai.message.api.vo.TMMessageVo;
import com.yinhai.message.core.bpo.IMessageBpo;
import com.yinhai.message.core.po.MessageFilePo;
import com.yinhai.message.core.sender.IMessageSender;
import com.yinhai.message.core.util.FTPUtils;
import com.yinhai.message.core.util.IMessageConstant;
import com.yinhai.message.manage.register.bpo.IEmailConfigBpo;
import com.yinhai.message.manage.register.vo.EmailConfigVo;

/**
 *
 * 具体的消息发送器实现发送消息和发送消息完的反馈
 * @author maxp
 * @Create 2016-12-29-14:28
 * @modified lanyc 2017-3-29
 */
@Service
public class EmailMessageSender implements IMessageSender<TMMessageVo>{
	
	
	@Override
    public List<TMUser> sendMessage(TMMessageVo emailVo){
		//查询附件
		IMessageBpo messageBpo = (IMessageBpo) ServiceLocator.getService("messageBpo");
		List<MessageFilePo> listPo = messageBpo.queryMessageFileByMsgid(emailVo.getMessage().getMgid());
		
		Email email = new Email();
		IEmailConfigBpo emailConfigBpo = (IEmailConfigBpo) ServiceLocator.getService("emailConfigBpo");
		EmailConfigVo configVo = emailConfigBpo.queryEmailConfigBySystemId(emailVo.getUser().getAppId());
		if (configVo != null && !StringUtils.isEmpty(configVo.getEmailAddress()) && !StringUtils.isEmpty(configVo.getSendHost())) {
			email.setFromAddress(emailVo.getUser().getName(), configVo.getEmailAddress());
			for (TMUser user : emailVo.getUserlist()) {
				if(ValidateUtil.isEmpty(user.getEmail())){
					continue;
				}
				email.addRecipient(user.getName(), user.getEmail(), Message.RecipientType.TO);
			}
			email.setTextHTML(emailVo.getMessage().getContent());
			email.setSubject(emailVo.getMessage().getTitle());
			for (MessageFilePo po : listPo) {
//				String mimetype = new MimetypesFileTypeMap().getContentType(po.getFilename());
				Path path = Paths.get(po.getFilename());
				String mimetype;
				try {
					mimetype = Files.probeContentType(path);
				} catch (IOException e1) {
					mimetype = "application/octet-stream";
				}
				String storeMode = po.getFilestoremode();
				InputStream ins = null;
				if (IMessageConstant.MSG_FILE_STORE_LOCAL.equals(storeMode)) {
					String realpath = po.getFilepath();
					File file = new File(realpath);
					try {
						ins = new FileInputStream(file);
					} catch (FileNotFoundException e) {
						throw new TMException(e);
					}
				} else if (IMessageConstant.MSG_FILE_STORE_FTPSERVER.equals(storeMode)) {
					FTPUtils ftpUtils = FTPUtils.getInstance();
					String serverName = SysConfig.getSysConfig("msgFileStorePlace");
					try {
						ins = ftpUtils.retrieveFile(serverName, po.getFilepath(), new String(po.getFilename().getBytes("GBK"),"iso-8859-1"));
					} catch (UnsupportedEncodingException e) {
						throw new TMException(e);
					}
				} else if (IMessageConstant.MSG_FILE_STORE_UNIFIED_STORE.equals(storeMode)) {

				}
				if (ins != null) {
					email.addAttachment(po.getFilename(), getBytes(ins), mimetype);
				}
			}
			Mailer mailer;
			if (configVo.getIsSendSSL() == 1) {
				mailer = new Mailer(configVo.getSendHost(), configVo.getSendPort(), configVo.getEmailAddress(), configVo.getPassword(), TransportStrategy.SMTP_SSL);
			} else if (configVo.getIsSendTLS() == 1) {
				mailer = new Mailer(configVo.getSendHost(), configVo.getSendPort(), configVo.getEmailAddress(), configVo.getPassword(), TransportStrategy.SMTP_TLS);
			} else {
				mailer = new Mailer(configVo.getSendHost(), configVo.getSendPort(), configVo.getEmailAddress(), configVo.getPassword());
			}
			mailer.sendMail(email);
		}else{
			throw new TMException("未获取到接入系统的邮箱配置 或 邮箱配置数据不完整");
		}
//		email.setFromAddress("tianhaoyun125018","tianhaoyun125018@163.com");
//		EmailConfigVo emailConfigVo = new EmailConfigVo("220.181.12.12",25,"tianhaoyun125018","tzh228115361");
		/*EmailConfigPo ecp = emailConfigBpo.queryEmailConfigInfo(emailAddress);
        new Mailer(ecp.getSendHost(),ecp.getSendPort(),ecp.getEmailAddress(),ecp.getPassword()).
                sendMail(TAMail.getSington().getMail(emailmessage));*/
		return emailVo.getUserlist();
    }
	
	public byte[] getBytes(InputStream ins){  
        byte[] buffer = null;  
        try {  
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
            byte[] b = new byte[1000];  
            int n;  
            while ((n = ins.read(b)) != -1) {  
                bos.write(b, 0, n);  
            }  
            ins.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return buffer;  
    }  
}
